package actions;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * 文件下载.
 * @author taotao
 */
public class CommonFileDownloadAction extends Action {

    /**
     * fileName必须是一个完整的绝对路径.
     * @param mapping action mapping
     * @param form action form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any exception
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String fileName = request.getParameter("fileName");
        if (fileName == null || fileName.equals("")) {
            fileName = (String) request.getAttribute("fileName");
        }
        String mimeType = request.getParameter("mimeType");
        mimeType = (mimeType != null) ? mimeType : servlet.getServletContext()
                .getMimeType(fileName);
        File file = new File(fileName);
        response.setHeader("Content-Type", mimeType + ";charset=UTF-8");
        response.addHeader("Content-disposition", "filename="
                + new String(file.getName().getBytes("UTF-8"), "ISO8859_1"));

        //
        sendTempFile(file, response.getOutputStream());
        return null;
    }

    /**
     * 将文件写入输出流.
     * @param file 输出的文件.
     * @param out OutputStream.
     * @throws IOException e
     */
    private void sendTempFile(File file, OutputStream out) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        BufferedOutputStream bos = new BufferedOutputStream(out);
        byte[] input = new byte[1024];
        boolean eof = false;
        while (!eof) {
            int length = bis.read(input);
            if (length == -1) {
                eof = true;
            } else {
                bos.write(input, 0, length);
            }
        }
        bos.flush();
        bis.close();
        bos.close();
    }

}